//加载模块
const express = require('express');
//声明express的Router方法
const router = express.Router();
const User = require('../models/User');
const Category = require('../models/Category')
const Content = require('../models/Content')

router.use(function(req, res, next) {
  let userInfo = req.cookies.userInfo || {}
  if(!userInfo.isAdmin) {
    res.send('对不起，只有管理员才有权限进入')
    return
  }
  next()
})

router.get('/', function(req, res, next) {
  let userInfo = req.cookies.userInfo || {}
  res.render('admin/index', {
    userInfo: userInfo
  })
})


// 用户首页
router.get('/user', function(req, res) {
  let userInfo = req.cookies.userInfo || {}

  //limit(Number):限制获取的数据条数
  //skip(Number):忽略的数据条数
  User.count().then(function(count) {

    //每页显示的条数
    let limit = 10;
    //总页数
    let pages = Math.ceil(count/limit);
    //当前为第几页
    let page = Number(req.query.page || 1);
    //对页数进行逻辑判断
    //1 请求的页数不能小于1
    //2 请求的页数不能大于总页数
    if(page < 1) page = 1;
    if(page > pages) page = pages
    //跳过的数据条数
    let skip = Number((page-1) * limit);

    //获取用户信息
    User.find().skip(skip).limit(limit).then(function(users) {
      res.render('admin/user', {
        userInfo: userInfo,
        users: users,
        page: page,
        pages: pages,
        limit: limit,
        url: 'user'
      })
    })
  })
})

// 分类首页
router.get('/category', function(req, res) {
  let userInfo = req.cookies.userInfo || {}

  // limit(Number):限制获取的条数
  // skip(Number):跳过的数据条数

  Category.count().then(function(count) {
    let limit = 10
    let pages = Math.ceil(count / limit)
    let page = Number(req.query.page || 1)
    let skip = limit * (page - 1)

    Category.find().skip(skip).limit(limit).then(function(categories) {
      res.render('admin/category', {
        categories: categories,
        pages: pages,
        page: page,
        limit: limit,
        url: 'category',
        userInfo: userInfo
      })
    })
  })
})

router.get('/category/add', function(req, res) {
  let userInfo = req.cookies.userInfo || {}
  res.render('admin/category_add', {
      userInfo: userInfo
  });
});

//分类的添加
router.post('/category/add', function(req, res) {
  let userInfo = req.cookies.userInfo || {}

  //获取提交过来的数据
  let name = req.body.name || ''

  //进行提交数据的逻辑判断
  //1 名称不能为空
  //2 名称不能重复
  if(name == '') {
    res.render('admin/error', {
      userInfo: userInfo,
      message: '名称不能为空'
    })
    return
  }
  Category.findOne({
    name: name
  }).then(function(category) {
    if (category) {
      res.render('admin/error', {
        message: '已经有此分类了，请勿重复添加',
        userInfo: userInfo
      })
      return
    } else {
      //将数据保存到数据库中
      let category = new Category({
        name: name
      })
      category.save();
      res.render('admin/success', {
        message: '添加成功',
        url: '/admin/category',
        userInfo: userInfo
      })
    }
  })
  return
})

//分类的删除
router.get('/category/delete', function(req, res) {
  let userInfo = req.cookies.userInfo || {}
  Category.remove({
    _id: req.query.id
  })
    .then(function() {
      res.render('admin/success', {
        message: '删除成功',
        url: '/admin/category',
        userInfo: userInfo
      })
      return
    })
})

//分类的修改
router.get('/category/edit', function(req, res) {
  let userInfo = req.cookies.userInfo || {}
  Category.findOne({
    _id: req.query.id
  }).then(function(category) {
    res.render('admin/category_edit', {
      category: category,
      userInfo: userInfo
    })
    return
  })
})

//分类的修改
router.post('/category/edit', function(req, res) {
  let userInfo = req.cookies.userInfo || {}

  //获取提交过来的数据
  let name = req.body.name || ''
  let id = req.query.id || ''

  //进行提交数据的逻辑判断
  //1 名称不能为空
  if(name == '') {
    res.render('admin/error', {
      userInfo: userInfo,
      message: '名称不能为空'
    })
    return
  }
  //将数据进行修改
  Category.findOne({
    _id: id
  }).then(function(category) {
    if(name == category.name) {
      res.render('admin/success', {
        message: '修改成功',
        url: '/admin/category'
      })
      return
    } else {
      res.render('admin/success', {
        message: '修改成功',
        url: '/admin/category'
      })
      return Category.update({
        _id: id
      }, {
        name: name
      })
    }
  })
})

//内容首页
router.get('/content', function(req, res) {
  let userInfo = req.cookies.userInfo || {}

  // limit(Number) 限制每页获取的数据条数
  // skip(Number) 跳过的数据条数
  // 获取所有的数据的条数
  Content.count().then(function(count) {

    let limit = 10
    let pages = Math.ceil(count / limit)
    let page = parseInt(req.query.page || 1)
    let skip = (page-1) * limit

    Content
      .find()
      .limit(limit)
      .skip(skip)
      .populate(['category'])
      .sort({_id: -1})
      .then(function(contents) {
        res.render('admin/content', {
          contents: contents,
          limit: limit,
          pages: pages,
          page: page,
          url: 'content',
          userInfo: userInfo
      })
    })
  })
})

//添加内容
router.get('/content/add', function(req, res) {
  let userInfo = req.cookies.userInfo || {}

  //获取数据库中分类的信息
  Category.find().sort({_id: 1}).then(function(categories) {
    res.render('admin/content_add', {
      categories: categories,
      userInfo: userInfo
    })
  })
})


//内容的保存
router.post('/content/add', function(req, res) {
  let userInfo = req.cookies.userInfo || {}

  if(req.body.title == '') {
    res.render('admin/error', {
      message: '请输入内容标题',
      userInfo: userInfo
    })
    return
  }
  if(req.body.author == '') {
    res.render('admin/error', {
      message: '请输入作者',
      userInfo: userInfo
    })
    return
  }

  new Content({
    category: req.body.category,
    title: req.body.title,
    author: req.body.author,
    contentIntro: req.body.contentIntro,
    content: req.body.content
  }).save()
    .then(function() {
      res.render('admin/success', {
        message: '添加成功',
        url: '/admin/content',
        userInfo: userInfo
      })
    return
  })
})

//内容的修改
router.get('/content/edit', function(req, res) {
  let userInfo = req.cookies.userInfo || {}

  let id = req.query.id
  let categories = []

  Category.find().sort({_id: 1}).then(function(rs) {
    categories = rs
    return Content.findOne({
      _id: id
    }).populate('category')
  })
    .then(function(content) {
      res.render('admin/content_edit', {
        categories :categories,
        content: content,
        userInfo: userInfo
    })
  })
})

//内容修改的保存
router.post('/content/edit', function(req, res) {
  let userInfo = req.cookies.userInfo || {}
  if(req.body.title == ''){
    res.render('admin/error', {
      message: '标题不能为空',
      userInfo: req.userInfo
    })
    return
  }
  if(req.body.author == '') {
    res.render('admin/error', {
      message: '作者不能为空',
      userInfo: userInfo
    })
    return
  }
  Content.update({
    _id: req.query.id
  }, {
    category: req.body.category,
    title: req.body.title,
    author: req.body.author,
    contentIntro: req.body.contentIntro,
    content: req.body.content
  }).then(function() {
    res.render('admin/success', {
      message: '修改成功',
      url: '/admin/content',
      userInfo: userInfo
    })
    return
  })
})

//内容的删除
router.get('/content/delete', function(req, res) {
  let userInfo = req.cookies.userInfo || {}
  Content.remove({
    _id: req.query.id
  }).then(function() {
    res.render('admin/success', {
      message: '删除成功',
      url: '/admin/content',
      userInfo: userInfo
    })
    return
  })
})

module.exports = router;
